package com.comdosoft.comdoandroidbase.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.comdosoft.comdoandroidbase.R;
import com.comdosoft.comdoandroidbase.adapter.MyAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.xiaolang.mobi1.logic.dto.Customer;

public class MapActivity extends Activity implements OnMapClickListener {
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	BitmapDescriptor mCurrentMarker;
	boolean isFirstLoc = true;// 是否首次定位
	private LatLng ll;

	private List<Customer> custs = new ArrayList<Customer>();
	// 地理编码
	GeoCoder mGeoCoder = null;
	private int index = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		SDKInitializer.initialize(getApplicationContext());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		float zoomLevel = Float.parseFloat("15");
		MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(zoomLevel);
		mBaiduMap.animateMapStatus(u);
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1);
		mLocClient.setLocOption(option);
		mLocClient.start();

		mGeoCoder = GeoCoder.newInstance();
		mGeoCoder.setOnGetGeoCodeResultListener(GeoListener);

		// 地图点击事件处理
			mBaiduMap.setOnMapClickListener(Clicklistener);
		confirm = (TextView) findViewById(R.id.confirm);

		confirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (custs.size() == 0)
					return;
				
					Intent i = new Intent();
					i.putExtra("adress", custs.get(index).getLxdz());
					i.putExtra("long", custs.get(index).getLongitude());
					i.putExtra("lat", custs.get(index).getLatitude());
					setResult(RESULT_OK, i);
					finish();
				

			}
		});
		initListView();

	}

	private void initListView() {
		list = (ListView) findViewById(R.id.map_list);
		myadapter = new MyAdapter(getApplicationContext(), custs);
		list.setAdapter(myadapter);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				index = position;
				myadapter.setIndex(position);
				myadapter.notifyDataSetChanged();

			}
		});
	}

	OnMapClickListener Clicklistener = new OnMapClickListener() {
		/**
		 * 地图单击事件回调函数
		 * 
		 * @param point
		 *            点击的地理坐标
		 */
		public void onMapClick(LatLng point) {
			// Toast.makeText(getApplicationContext(), point.toString(),
			// 1000).show();

			mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
					.location(point));
		}

		/**
		 * 地图内 Poi 单击事件回调函数
		 * 
		 * @param poi
		 *            点击的 poi 信息
		 */
		public boolean onMapPoiClick(MapPoi poi) {
			return true;
		}
	};
	// 地理编码监听器
	OnGetGeoCoderResultListener GeoListener = new OnGetGeoCoderResultListener() {

		public void onGetGeoCodeResult(GeoCodeResult result) {

			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				// 没有检索到结果
			}
			// 获取地理编码结果
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {

			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				// 没有找到检索结果
			}
			// 获取反向地理编码结果
			else {
				// 当前位置信息
				custs.clear();
				try {
					for (int i = 0; i < result.getPoiList().size(); i++) {
						// Toast.makeText(getApplicationContext(),
						// result.getPoiList().get(i).address, 1000).show();
						// Log.i(result.getPoiList().get(i).address +
						// result.getLocation(), result
						// .getLocation().toString());
						Customer ct = new Customer();
						ct.setLxdz(result.getPoiList().get(i).address);
						ct.setLongitude(String.valueOf(result.getPoiList().get(
								i).location.longitude));
						ct.setLatitude(String.valueOf(result.getPoiList()
								.get(i).location.latitude));
						custs.add(ct);
					}
				} catch (Exception e) {
				}
				index = 0;
				myadapter.setIndex(0);
				myadapter.notifyDataSetChanged();
			}
		}
	};
	private ListView list;
	private MyAdapter myadapter;
	private TextView confirm;
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;

			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;				
				ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
				

				mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption())
						.location(ll));
				// NewToast.makeText(getApplicationContext(),
				// ll.longitude+"+"+ll.latitude, 1000);
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	protected void onPause() {
		if (mMapView != null)
			mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (mMapView != null)
			mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMapPoiClick(MapPoi arg0) {
		// TODO Auto-generated method stub
		return false;
	}
}
